package com.example.job;

import com.example.domain.entity.Article;
import com.example.exception.FloraException;
import com.example.service.ArticleService;
import com.example.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class UpdateViewCountJob {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private RedisCache redisCache;

    @Scheduled(cron = "* 0/10 * * * ?")
    public void updateViewCount() throws FloraException {
        //获取redis中浏览量
        Map<String,Integer> viewCountMap = redisCache.getCacheMap("ArticleViewCount");

        List<Article> articleList = articleService.list();
        for(String key:viewCountMap.keySet()){
            //更新数据库浏览量时文章可能已经被删除
            Article article = articleService.getById(Long.valueOf(key));
            if(article==null){
                // throw new FloraException("文章已被删除，无法更改浏览量");
            }
            else {
                article.setViewCount(Long.valueOf(viewCountMap.get(key)));
                articleService.updateById(article);
            }
        }
    }

}
